package tomcat.ch01;

import java.io.*;
import java.net.Socket;

/**
 * date : 2018年08月02日
 */
public class FirstSocket {

    /**
     * Exception in thread "main" java.net.ConnectException: Connection refused
     *
     * @param args
     * @throws IOException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        // 这使用了`try-with-resource`(IDEA的推荐)
        // 书中代码`Socket`构造函数的第二个参数`port`是字符串参数,但是现在只有int型的参数了.
        try (Socket socket = new Socket("127.0.0.1", 8080)) {
            OutputStream os = socket.getOutputStream();
            boolean autoflush = true;
            PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // send a HTTP request to the web server
            out.println("GET /index.jsp HTTP/1.1");
            out.println("Host: localhost:8080");
            out.println("Connection: Close");
            out.println();

            // read the response
            boolean loop = true;
            StringBuffer sbb = new StringBuffer(8096);
            while (loop){
                if(in.ready()){
                    int i = 0;
                    while (i != -1){
                        i = in.read();
                        sbb.append((char)i);
                    }
                    loop = false;
                }

                Thread.currentThread().sleep(50);
            }

            // display the response to the out console
            System.out.println(sbb.toString());
            //socket.close();
        }
    }
}
